<template>
  <PageContainer>
    <view class="container">
      <Header title="我的推广" />
      <view class="bgf">
        <view class="p-16">
          <StatisticsCard :datas="datas" title="推广数据总览" item-width="196rpx"></StatisticsCard>
        </view>
        <view class="py-13 px-16 fz-16 default-colo linh-24">我的推广记录</view>
        <view class="py-6 px-16" style="height: 72rpx">
          <TSearch placeholder="搜索供需名称" @confirm="searchConfirm"></TSearch>
        </view>
      </view>
      <view class="p-16">
        <Paglist
          v-model="dataList"
          :is-init-api="true"
          :parame="parame"
          @register="register"
          :scroll-top-bottom="260"
          :is-show-loadmore="dataList.length >= 1"
        >
          <template v-for="v in dataList" :key="v.id">
            <view class="mb-12">
              <promotionRecordItem :data="v" @share="handleShare"></promotionRecordItem>
            </view>
          </template>
        </Paglist>
      </view>
    </view>
  </PageContainer>
  <CustomShare v-model:visible="showSharePopup" :z-index="999" @register="customShareRegister" />
</template>

<script lang="ts" setup>
  /* extensionCenter 推广中心 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import StatisticsCard from '../components/StatisticsCard/index.vue';
  import { onMounted, provide, reactive, ref } from 'vue';
  import TSearch from '@/components/TSearch/index.vue';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import promotionRecordItem from './components/promotionRecordItem.vue';
  import {
    boUserPromotionCountDataList,
    getPromotionStatistics,
  } from '@/api/businessOpportunities';
  import type { IPromotionRecord } from '@/api/businessOpportunities/type';
  import type { IQuery } from '@/api/indexTypes';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { addAppShareLog } from '@/api';
  import { createMiniCode, toSelectiveType } from '@/utils/dynamicConfig';
  import { onPageScroll, onShareAppMessage } from '@dcloudio/uni-app';
  import { useUserStore } from '@/store/modules/user';
  import { createShareQuery, useAppShare } from '@/hooks/core/useAppShare';
  import { getSupplyDemandPosterData, getSupplyDemandWxShareData } from '../components/utils';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';

  const datas = ref([
    { name: '推广供需数', num: 120, unit: '个' },
    { name: '累计浏览次数', num: 120, unit: '次' },
    { name: '累计浏览人数', num: 112, unit: '个' },
    { name: '累计意向', num: 1200, unit: '个' },
    { name: '已联系', num: 120, unit: '个' },
  ]);

  provide('api', boUserPromotionCountDataList);
  const dataList = ref<IPromotionRecord[]>([]);
  const parame = reactive<IQuery & { keyWord: string }>({
    current: 1,
    size: 10,
    keyWord: '',
  });
  const [register, { refresh }] = useConList();

  const searchConfirm = (val: string) => {
    parame.keyWord = val;
    refresh();
  };

  const queryPromotionStatistics = async () => {
    const res = await getPromotionStatistics();
    datas.value[0].num = res.boNum;
    datas.value[1].num = res.browseNum;
    datas.value[2].num = res.browsePeopleNum;
    datas.value[3].num = res.cooperationNum;
    datas.value[4].num = res.cooperationSuccessNum;
  };

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    { setWxShareOptions, setShareLogId, setPosterDrawData, setButtons, setInternalLinkOptions },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  const { setWxSharePath } = useAppShare();

  const shareCache = new Map<number, { codeImg: string; shareLogId: number; posterImg: string }>(
    [],
  );
  const handleShare = async (item: IPromotionRecord) => {
    const shareCacheItem = shareCache.get(item.boInfoId);
    if (!shareCacheItem) {
      uni.showLoading({ title: '分享参数准备中...', mask: true });
    }

    const query = { id: item.boInfoId };
    const path = setWxSharePath({
      name: 'supplyDemandDetails',
      options: query,
    });
    setInternalLinkOptions({
      name: 'supplyDemandDetails',
      options: query,
    });

    const routeQuery = createShareQuery(query);
    await setWxShareOptions([getSupplyDemandWxShareData(item, path)]);
    let shareLogId = shareCacheItem?.shareLogId;
    let codeImg = shareCacheItem?.codeImg;
    if (!shareCache.has(item.boInfoId)) {
      const res = await addAppShareLog({
        path: 'supplyDemandDetails',
        query: JSON.stringify(routeQuery),
      });
      shareLogId = res.id;
      codeImg = await createMiniCode({ shareLogId });
      const posterData = getSupplyDemandPosterData(item, codeImg);
      const posterImgs = await setPosterDrawData([posterData]);
      shareCache.set(item.boInfoId, { codeImg, shareLogId, posterImg: posterImgs[0] });
      setButtons({
        share: true,
        poster: true,
        copyLink: true,
        insertOffiaccount: true,
      });
      uni.hideLoading();
    } else {
      setButtons({
        share: true,
        poster: !!shareCacheItem?.posterImg,
        copyLink: true,
        insertOffiaccount: true,
      });
      await setPosterDrawData([shareCacheItem?.posterImg || '']);
    }

    setShareLogId(shareLogId as number);
    showSharePopup.value = true;
  };

  onShareAppMessage(() => ({}));

  onPageScroll(() => {});

  wx.hideShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
  });

  onMounted(() => {
    queryPromotionStatistics();
  });
</script>

<style lang="scss" scoped></style>
